import java.net.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.io.*;

public class threadpooltcpserver {
	public static void main(String[] args) throws IOException {

		int port = 1234;
		ServerSocket listenSocket = new ServerSocket(port);

		int corePoolSize = 5;
		int maximumPoolSize = 10;
		long keepAliveTime = 500;

		ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
		 TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(5));

		while (true) {
			serverTask task = new serverTask(listenSocket.accept());
			executor.execute(task);
		}

	}

	static class serverTask implements Runnable {

		private Socket clientsocket = null;

		public serverTask(Socket s) {
			this.clientsocket = s;
		}

		@Override
		public void run() {
			try {
				InputStream in = this.clientsocket.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));

				OutputStream out = this.clientsocket.getOutputStream();
				PrintWriter print = new PrintWriter(out);

				String receive = null;
				while ((receive = reader.readLine()) != null) {
					// Thread.sleep(5000);
					System.out.println("Server receive: " + receive);
					System.out.println("Current thread Id: "+Thread.currentThread().getId());
					String back = "from server: " + receive;
					print.println(back);
					print.flush();
				}
				reader.close();

			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					this.clientsocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}